package com.siashan.unipay4j.ali.bill;

import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.siashan.unipay4j.ali.AbstractAliPay;
import com.siashan.unipay4j.core.IPayConfig;
import com.siashan.unipay4j.core.PayChannel;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.bill.BillModel;
import com.siashan.unipay4j.core.bill.BillResponse;
import com.siashan.unipay4j.core.bill.IBillDownload;
import lombok.extern.slf4j.Slf4j;

/**
 * 账单下载类
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public class AliPayBillDownload extends AbstractAliPay implements IBillDownload {
    public AliPayBillDownload() {
    }

    public AliPayBillDownload(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 下载对账单
     * @param billModel  账单请求参数
     * @return 账单
     */
    @Override
    public Result<BillResponse> execDown(BillModel billModel) {
        log.info("AliBillDownload::=>请求到达，账单日期{}", billModel.getBillDate());
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        request.setBizContent("{" +
                "\"bill_type\":\""+billModel.getBillType()+"\"," +
                "\"bill_date\":\"" + billModel.getBillDate() + "\"" +
                "  }");
        try {
            AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                return Result.tradeSuccess(wrapBillResponse(response));
            } else {
                return Result.returnFail(response.getSubCode(), response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.info("WxBillDownload::=>下载对账单发生异常,账单类型{}", billModel.getBillDate());
        }
        return Result.exception();
    }

    private BillResponse wrapBillResponse(AlipayDataDataserviceBillDownloadurlQueryResponse r){
        BillResponse response = new BillResponse();
        response.setPayChannel(PayChannel.ALI);
        response.setBillDownUrl(r.getBillDownloadUrl());
        return response;
    }
}
